package com.atguigu.kafka.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

/**
 * @author: 叶子
 * @date: 2022/08/14 23:00
 * 使用事务，必须手动指定事务id
 **/
public class CustomProducerTransaction {
    public static void main(String[] args) {
        //0 配置
        Properties properties = new Properties();
        //连接集群
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka130:9092,kafka131:9093,kafka132:9094");
        //指定对应的key和value的序列化类型，下面这一行注释与代码是相同的含义，建议使用StringSerializer.class
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        //指定事务id
        properties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "transaction_id_001");
        //1.创建 kafka 生产者对象
        KafkaProducer kafkaProducer = new KafkaProducer<String, String>(properties);
        kafkaProducer.initTransactions();
        kafkaProducer.beginTransaction();
        try {
            //2.发送数据
            for (int i = 0; i < 5; i++) {
                kafkaProducer.send(new ProducerRecord<>("firstTopic", "dage" + i));
            }
//            int i = 1/0;//模拟事务失败
            kafkaProducer.commitTransaction();
        } catch (Exception e) {
            kafkaProducer.abortTransaction();
        } finally {
            //3.关闭资源
            kafkaProducer.close();
        }
    }
}